package com.shouhuobao.bhi.stamp;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.alipay.PayResult;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.StampOrderBean;
import com.collectplus.express.model.StampOrderItemBean;
import com.collectplus.express.wxapi.WXPayEntryActivity;
import com.shb.model.OrderPayBean;
import com.shb.model.WxPayModel;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;

/**
 * 邮票收银台
 *
 * @author kaka <br>
 *         2017年5月3日
 */
public class StampOrderPayActivity extends BaseActivity2 implements OnClickListener {

    private StampOrderBean order;

    private CheckBox mWxButton, mAliButton;
    private Button mOkButton;

    private final int SDK_PAY_FLAG = 3;
    private final int SDK_CHECK_FLAG = 4;

    private BroadcastReceiver wxCallBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        order = (StampOrderBean) getIntent().getSerializableExtra("stamp_order");
        super.onCreate(savedInstanceState);
        wxCallBack = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                showToast("邮票购买成功!");
                AppHttp.getInstance().stampPayCallBack(order.getOrderId(), 1, 0);
                StampOrderPayActivity.this.setResult(Activity.RESULT_OK);
                finish();
            }
        };
        IntentFilter intentFilter = new IntentFilter("wxpay_callback");
        registerReceiver(wxCallBack, intentFilter);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.stamp_order_pay);
        super.findViewById();
        getAppTitle().setCommonTitle("收银台");

        findViewById(R.id.pay_wx_layout).setOnClickListener(this);
        findViewById(R.id.pay_ali_layout).setOnClickListener(this);
        mWxButton = (CheckBox) findViewById(R.id.pay_wx_checkBox);
        mAliButton = (CheckBox) findViewById(R.id.pay_ali_checkBox);
        mAliButton.setChecked(true);
        mOkButton = (Button) findViewById(R.id.pay_ok_button);
        mOkButton.setOnClickListener(this);

        LinearLayout listParent = (LinearLayout) findViewById(R.id.stamp_list_parent);
        TextView stampPrice = (TextView) findViewById(R.id.stamp_price);

        stampPrice.setText("总计:￥" + order.getCost());
        ArrayList<StampOrderItemBean> stamps = order.getStamps();
        for (int i = 0; i < stamps.size(); i++) {
            StampOrderItemBean itemBean = stamps.get(i);
            View item = getLayoutInflater().inflate(R.layout.stamp_order_item, null);
            TextView stampName = (TextView) item.findViewById(R.id.stamp_name);
            TextView stampCount = (TextView) item.findViewById(R.id.stamp_count);
            TextView stampItemPrice = (TextView) item.findViewById(R.id.stamp_price);
            stampName.setText(itemBean.getStampName());
            stampCount.setText(itemBean.getStampNum() + "张");
            stampItemPrice.setText("￥" + itemBean.getTotalPrice());
            listParent.addView(item);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.pay_wx_layout:
                mWxButton.setChecked(true);
                mAliButton.setChecked(false);
                break;
            case R.id.pay_ali_layout:
                mAliButton.setChecked(true);
                mWxButton.setChecked(false);
                break;
            // 支付、提交订单
            case R.id.pay_ok_button:
                payMoney();
                break;
            default:
                break;
        }
    }

    /**
     * 支付方法
     */
    public void payMoney() {
        if (mAliButton.isChecked()) {
            showLoadingDialog(null);
            //
            AppHttp.getInstance().stampAliPay(order.getOrderId(), order.getCost() + "", order.getCost() + "", 0);
        } else if (mWxButton.isChecked()) {
            final IWXAPI wxapi = WXAPIFactory.createWXAPI(this, null);
            if (wxapi.isWXAppInstalled() == false) {
                showToast("未安装微信");
                return;
            }
            showLoadingDialog(null);
            WXPayEntryActivity.payFrom = 1;
            AppHttp.getInstance().stampWeiXinPay(order.getOrderId(), order.getCost() + "", order.getCost() + "", 0);
        } else {
            showToast("请选择支付方式");
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.stamp_wxpay:
                cancelLoadingDialog();
                AppResult<WxPayModel> wxResult = JSON.parser(msg.obj.toString(), WxPayModel.class);
                if (wxResult == null) {
                    return true;
                }
                switch (wxResult.getStatus()) {
                    case 1:
                        WxPayModel wxModel = wxResult.getResult();
                        if (wxModel == null) {
                            return true;
                        }
                        com.shb.model.OrderPayBean pay = new com.shb.model.OrderPayBean(wxModel);
                        // Intent intent = new Intent();
                        // intent.setClass(getContext(), WXPayServerActivity.class);
                        // intent.putExtra("pay", pay);
                        // startActivity(intent);

                        handleWxpay(pay);
                        break;
                    case 0:
                        break;
                }
                return true;
            case MsgID.stamp_alipay:
                cancelLoadingDialog();
                AppResult<?> aliResult = JSON.parser(msg.obj.toString());
                if (aliResult.getResult() == null) {
                    showToast("服务器异常");
                    return true;
                }
                switch (aliResult.getStatus()) {
                    case 1:
                        alipay(aliResult.getResult().toString());
                        break;
                    case 0:
                        break;
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    /**
     * 处理跳转到微信支付
     *
     * @param pay
     */
    private void handleWxpay(OrderPayBean pay) {
        if (pay == null) {
            Toast.makeText(this, "订单数据异常", Toast.LENGTH_SHORT).show();
        } else {
            sendPayReq(pay);
        }
    }

    private void sendPayReq(OrderPayBean pay) {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(pay.getAppid());
        //
        PayReq req = new PayReq();
        if (getIntent() != null) {
            String isCollect = getIntent().getStringExtra("isCollect");
            if (isCollect != null) {
                req.extData = isCollect;
            }
        }
        req.appId = pay.getAppid();
        req.partnerId = pay.getPartnerid();
        req.prepayId = pay.getPrepayid();
        req.packageValue = pay.getPackageValue();
        req.nonceStr = pay.getNoncestr();
        req.timeStamp = pay.getTimestamp();
        req.sign = pay.getSign();
        //
        msgApi.sendReq(req);
    }

    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public void alipay(final String payInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(StampOrderPayActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mPayHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mPayHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    // String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(StampOrderPayActivity.this, "邮票购买成功!", Toast.LENGTH_SHORT).show();
                        // startActivity(new Intent(OrderPayActivity.this, OrderEvaluateActivity.class));
                        // AppLogic.getInstance().onPaySuccess(getContext());
                        AppHttp.getInstance().stampPayCallBack(order.getOrderId(), 2, 0);
                        StampOrderPayActivity.this.setResult(Activity.RESULT_OK);
                        StampOrderPayActivity.super.finish();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(StampOrderPayActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                        }
                        // 6001代表支付取消
                        if (TextUtils.equals(resultStatus, "6001")) {

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(StampOrderPayActivity.this, "支付失败，请重试！", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(StampOrderPayActivity.this, "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onDestroy() {
        if (wxCallBack != null) {
            unregisterReceiver(wxCallBack);
        }
        super.onDestroy();
    }
}
